<template>
  <canvas id="bg-canvas"></canvas>
</template>

<script setup>
import { onMounted, onBeforeUnmount } from 'vue';

let animationId = null;
let particles = [];
const PARTICLE_NUM = 60;
const PARTICLE_COLOR = 'rgba(255,255,255,0.85)';
const LINE_COLOR = 'rgba(255,255,255,0.13)';
const MAX_DIST = 120;

function resizeCanvas(canvas) {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
}

function createParticles(canvas) {
    particles = [];
    for (let i = 0; i < PARTICLE_NUM; i++) {
        particles.push({
            x: Math.random() * canvas.width,
            y: Math.random() * canvas.height,
            vx: (Math.random() - 0.5) * 0.7,
            vy: (Math.random() - 0.5) * 0.7,
            r: Math.random() * 1.2 + 0.8
        });
    }
}

function drawParticles(ctx, canvas) {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    // 画粒子
    for (let p of particles) {
        ctx.beginPath();
        ctx.arc(p.x, p.y, p.r, 0, 2 * Math.PI);
        ctx.fillStyle = PARTICLE_COLOR;
        ctx.shadowColor = '#fff';
        ctx.shadowBlur = 10;
        ctx.fill();
    }
    // 画连线
    for (let i = 0; i < particles.length; i++) {
        for (let j = i + 1; j < particles.length; j++) {
            const dx = particles[i].x - particles[j].x;
            const dy = particles[i].y - particles[j].y;
            const dist = Math.sqrt(dx * dx + dy * dy);
            if (dist < MAX_DIST) {
                ctx.beginPath();
                ctx.moveTo(particles[i].x, particles[i].y);
                ctx.lineTo(particles[j].x, particles[j].y);
                ctx.strokeStyle = LINE_COLOR;
                ctx.lineWidth = 1.1 - dist / MAX_DIST;
                ctx.globalAlpha = 1 - dist / MAX_DIST;
                ctx.stroke();
                ctx.globalAlpha = 1;
            }
        }
    }
}

function updateParticles(canvas) {
    for (let p of particles) {
        p.x += p.vx;
        p.y += p.vy;
        if (p.x < 0 || p.x > canvas.width) p.vx *= -1;
        if (p.y < 0 || p.y > canvas.height) p.vy *= -1;
    }
}

function animate(canvas, ctx) {
    updateParticles(canvas);
    drawParticles(ctx, canvas);
    animationId = requestAnimationFrame(() => animate(canvas, ctx));
}

onMounted(() => {
    const canvas = document.getElementById('bg-canvas');
    if (!canvas) return;
    resizeCanvas(canvas);
    createParticles(canvas);
    const ctx = canvas.getContext('2d');
    animate(canvas, ctx);
    window.addEventListener('resize', () => {
        resizeCanvas(canvas);
        createParticles(canvas);
    });
});

onBeforeUnmount(() => {
    if (animationId) cancelAnimationFrame(animationId);
});
</script>

<style>
#bg-canvas {
  position: fixed;
  left: 0;
  top: 0;
  width: 100vw;
  height: 100vh;
  z-index: 0;
  pointer-events: none;
}
</style> 